import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import api from '@/utils/api'
import { storeLogger } from '@/utils/logger'

export const useSavepointsStore = defineStore('savepoints', () => {
  // 状态
  const savepoints = ref([])
  const loading = ref(false)
  const total = ref(0)           // 当前筛选条件下的总数（用于分页）
  const totalAll = ref(0)        // 全部数据的总数（用于统计卡片显示）
  const currentPage = ref(1)
  const pageSize = ref(20)
  
  // 搜索条件
  const searchForm = ref({
    job_name: '',
    trigger_reason: '',
    fields: []
  })
  
  // 排序条件（默认按创建时间降序）
  const sortField = ref('creation_time')
  const sortOrder = ref('desc')
  
  // 获取全部数据总数（无搜索条件）
  // 注意：现在后端在每次请求中都会返回全局统计，这个方法已不再需要单独调用
  const fetchAllStats = async () => {
    try {
      const response = await api.get('/savepoints', { 
        params: { page: 1, size: 20 } // 只获取第一页即可，统计数据会一起返回
      })
      const payload = response.data || {}
      const data = payload.success ? (payload.data || {}) : payload
      
      // 后端现在直接返回全局统计
      if (data.hasOwnProperty('total_all')) {
        totalAll.value = data.total_all
      }
      
      storeLogger.info('Savepoints total count fetched successfully', { 
        totalAll: totalAll.value
      })
    } catch (error) {
      storeLogger.error('Failed to fetch savepoints total count', error)
    }
  }
  
  // 获取Savepoint列表
  const fetchSavepoints = async (params = {}) => {
    try {
      loading.value = true
      const queryParams = {
        page: currentPage.value,
        size: pageSize.value,
        sort: sortField.value,
        order: sortOrder.value,
        ...searchForm.value,
        ...params
      }
      
      // 如果传入了排序参数，覆盖默认排序
      if (params.sort) {
        sortField.value = params.sort
        queryParams.sort = params.sort
      }
      if (params.order) {
        sortOrder.value = params.order
        queryParams.order = params.order
      }
      
      // 清理空值
      Object.keys(queryParams).forEach(key => {
        if (queryParams[key] === '' || queryParams[key] === null || queryParams[key] === undefined) {
          delete queryParams[key]
        }
      })
      
      const response = await api.get('/savepoints', { params: queryParams })
      const payload = response.data || {}
      const data = payload.success ? (payload.data || {}) : payload
      savepoints.value = data.rows || []
      // 确保使用后端返回的真实总数，即使为0也要使用
      total.value = data.hasOwnProperty('total') ? data.total : savepoints.value.length
      
      // 后端现在直接返回全局统计数据（不管是否有筛选条件）
      if (data.hasOwnProperty('total_all')) {
        totalAll.value = data.total_all
      }
      return payload
    } catch (error) {
      storeLogger.error('获取Savepoint列表失败:', error)
      ElMessage.error('获取Savepoint列表失败')
      throw error
    } finally {
      loading.value = false
    }
  }
  
  // 重置搜索条件
  const resetSearch = () => {
    searchForm.value = {
      job_name: '',
      trigger_reason: '',
      fields: []
    }
    currentPage.value = 1
  }
  
  return {
    // 状态
    savepoints,
    loading,
    total,
    totalAll,
    currentPage,
    pageSize,
    searchForm,
    sortField,
    sortOrder,
    
    // 方法
    fetchSavepoints,
    fetchAllStats,
    resetSearch
  }
})